import socket


def udp_server():
    # 创建UDP套接字
    # AF_INET表示使用IPv4，SOCK_DGRAM表示使用UDP协议
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    # 绑定端口，空字符串表示监听所有可用的网络接口
    server_address = ('', 6666)
    print(f"开始监听UDP端口 {server_address[1]}...")
    server_socket.bind(server_address)

    try:
        while True:
            # 接收数据，缓冲区大小为1024字节
            data, client_address = server_socket.recvfrom(1024)
            print(f"收到来自 {client_address} 的消息: {data.decode('utf-8')}")

            # 准备回复消息
            response = f"已收到消息: {data.decode('utf-8')}".encode('utf-8')

            # 发送回复
            server_socket.sendto(response, client_address)
            print(f"已向 {client_address} 发送回复\n")

    except KeyboardInterrupt:
        print("\n用户中断，服务器关闭")
    finally:
        # 关闭套接字
        server_socket.close()
        print("服务器已关闭")


if __name__ == "__main__":
    udp_server()
